package com.test.router.system.service;

import com.test.router.system.core.BaseService;
import com.test.router.system.core.ResultResp;
import com.test.router.system.service.resources.IAPIDispatcherService;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class APIDispatcherServiceImpl extends BaseService implements IAPIDispatcherService {

    @Resource
    private RestTemplate restTemplate;


    @Override
    public ResultResp<Map<String, Object>> getForObject(String name, Object... uriVariables) {
        return restTemplate.getForObject("http://api-server/" + name, ResultResp.class);
    }

    @Override
    public ResultResp<Map<String, Object>> postForObject(String name, Map<String, Object> body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> data = new HttpEntity<>(body,headers);

        ResponseEntity<ResultResp> resp = restTemplate.postForEntity("http://api-server/" + name , data, ResultResp.class);
        return resp.getBody();
    }

    @Override
    public ResultResp<Map<String, Object>> putForObject(String name, Integer id, Map<String, Object> body) {
        HttpEntity<Map<String, Object>> data = new HttpEntity<>(body);
        ResponseEntity<ResultResp> resp = restTemplate.exchange("http://api-server/" + name + "/{1}", HttpMethod.PUT, data, ResultResp.class, id);
        return resp.getBody();
    }

    @Override
    public ResultResp<Map<String, Object>> deleteForObject(String name, Integer id) {
        ResponseEntity<ResultResp> resp = restTemplate.exchange("http://api-server/" + name + "/{1}", HttpMethod.PUT, null, ResultResp.class, id);
        return resp.getBody();
    }
}
